package com.baizhi.config;

import com.baizhi.service.MyUserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * ClassName: WebSecurityConfig
 * Description:
 * Date: 2022/11/06 AM 1:16
 * <p>
 * project: codes
 * package: com.baizhi.config
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyUserDetailServiceImpl myUserDetailService;

    /**
     * 使用 passwordEncoder 第二种方式
     *
     * @return passwordEncoder
     */
    //@Bean
    //public PasswordEncoder passwordEncoder() {
    //    return new BCryptPasswordEncoder();
    //}

    //@Bean
    //public UserDetailsService userDetailService() {
    //    InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
    //    // 第一种使用 passwordEncoder 方式
    //    //inMemoryUserDetailsManager.createUser(User.withUsername("root").password("{bcrypt}$2a$10$O6zXQFBuobrqY8VzfP.yb.Phail9MTS2zfNRTyR615Sc/Ndvt8gh6").roles("admin").build());
    //    inMemoryUserDetailsManager.createUser(User.withUsername("root").password("$2a$10$O6zXQFBuobrqY8VzfP.yb.Phail9MTS2zfNRTyR615Sc/Ndvt8gh6").roles("admin").build());
    //    return inMemoryUserDetailsManager;
    //}

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // auth.userDetailsService(userDetailService());
        auth.userDetailsService(myUserDetailService);
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .csrf().disable();
    }
}
